import com.mit.web.business.proxy.InventoryProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.util.FlexUtil;
import com.mit.web.util.LogUtil;
import com.mit.web.util.Validator;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.vo.inventory.WarehouseVO;

import flash.events.MouseEvent;

import mx.collections.ArrayCollection;
import mx.events.DataGridEvent;
import mx.events.FlexEvent;
import mx.logging.ILogger;
import mx.resources.ResourceManager;
import mx.rpc.events.ResultEvent;


[Bindable] private var _ds:ArrayCollection;
private var _pm:IProgressMonitor;
private var _proxy:InventoryProxy = InventoryProxy.getInstance();
private var _logger:ILogger;

private function init(event:FlexEvent):void{
	_logger = LogUtil.getLogger(this);
	doRetrieve();
}

private function doRetrieve():void{
	var responder:IInvokeResponder = _proxy.getWarehouses().installProgressBar(_pm, this);	
	responder.addResultListener(retrieveListHandler);
	responder.addFaultListener(exceptionHandler);
}

private function retrieveListHandler(event:ResultEvent):void{
	_ds = event.result as ArrayCollection;
	dg.validateNow();
}

//如果是工厂性质的仓库，则不能编辑
private function itemEditBeginHandler(event:DataGridEvent):void{
	var warehouse:WarehouseVO = _ds[event.rowIndex];
	if(warehouse.isFactory == Constants.YES){
		dg.editedItemPosition = null;
	}
}

private function doNew(event:MouseEvent):void{
	var newWarehouse:WarehouseVO = new WarehouseVO();
	newWarehouse.isFactory = Constants.NO;
	_ds.addItem(newWarehouse); 
	dg.validateNow();
	dg.editedItemPosition = {columnIndex:0, rowIndex:  _ds.length - 1};
}

private function doSave(event:MouseEvent):void{
	//Auto remove newly created empty record
	var clone:ArrayCollection = new ArrayCollection();
	clone = FlexUtil.deepClone(_ds) as ArrayCollection;
	for each(var o:WarehouseVO in clone){
		if(o.id < 1 
			&& (Validator.isNullOrBlank(o.name))
			&& (Validator.isNullOrBlank(o.address))
			&& (Validator.isNullOrBlank(o.tel)))
			_ds.removeItemAt(_ds.getItemIndex(o));
	}
	dg.validateNow();
	
	//validation to privent duplicate record
	//Why not validate when users focus out? because it will prevent users switching the name or  the code.
	if(!validate()){
		event.preventDefault();
		return;
	}

	var responder:IInvokeResponder = _proxy.saveWarehouses(_ds).installProgressBar(_pm, this);
	responder.addResultListener(savedHandler);
	responder.addFaultListener(exceptionHandler);

}

private function savedHandler(event:ResultEvent):void{
	retrieveListHandler(event);
	showMessageTip(ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"info.common.saveOk"),  dg);
	
}

private function validate():Boolean{
	var clone:ArrayCollection = new ArrayCollection();
	clone = FlexUtil.deepClone(_ds) as ArrayCollection;
	for each(var o:WarehouseVO in _ds){
		var id:int = o.id;
		var name:String = o.name;
		var address:String = o.address;
		var hasError:Boolean = false;
		var myError:String;
		if(Validator.isNullOrBlank(o.name)){
			myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.requiredField");
			dg.editedItemPosition = {columnIndex:0, rowIndex: _ds.getItemIndex(o)};
			hasError = true;
		}else if(Validator.isNullOrBlank(o.address) ){
			myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.requiredField");
			dg.editedItemPosition = {columnIndex:1, rowIndex: _ds.getItemIndex(o)};
			hasError = true;
		}
		
		if(!hasError){
			for each(var c:WarehouseVO in clone){
				//名字不能重复
				if(name == c.name && clone.getItemIndex(c) != _ds.getItemIndex(o)){
					//duplicate name
					myError = ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"error.common.duplicateKey",[name]);
					dg.editedItemPosition = {columnIndex:0, rowIndex: _ds.getItemIndex(o)};
					hasError = true;
					break;
				}
			}
		}
		
		if(hasError){
			
			showVerticalMiddleErrorTipAt(myError, dg);
			return false;
		}
	}
	return true;
}